package com.jlf.core.mp.util;

import com.baomidou.mybatisplus.core.override.MybatisMapperProxy;
import com.jlf.core.annotation.Domain;
import com.jlf.core.annotation.DomainRepository;
import com.jlf.core.mp.mapper._SimpleDao;
import org.joor.Reflect;

import java.lang.reflect.Field;
import java.util.concurrent.ConcurrentHashMap;

/**
 * mybatis-plus的领域辅助工具
 *
 * @author wujr
 * 2023/7/4
 * @version 1.0
 * 【变更历史】
 * [wujr 2023/7/4 1.0 新增]
 */
public class DomainHelper {
    /**
     * 领域模型的名称映射
     * key——SimpleDao的类的bean对象
     * value——该dao对应的领域的名称 {@link Domain#name()}
     */
    protected static final ConcurrentHashMap<Object, String> _mapDaoOfNames = new ConcurrentHashMap<>();

    public static String getName(Object mapper){
        return _mapDaoOfNames.computeIfAbsent(mapper, DomainHelper::parseDomainName);
    }
    protected static String parseDomainName(Object mapper){
        Class<?> thisClass = mapper.getClass();
        if (!(thisClass.isAssignableFrom(_SimpleDao.class))) {
            try {
                Field field = thisClass.getSuperclass().getDeclaredField("h");
                field.setAccessible(true);
                MybatisMapperProxy<?> proxy = (MybatisMapperProxy<?>) field.get(mapper);
                thisClass = Reflect.on(proxy).get("mapperInterface");
            } catch (Exception ignored) {
            }
        }
        return DomainRepository.name(thisClass);
    }
}
